POJ-2387 Til the Cows Come Home (Dijkstra or SPFA 水题)

描述

传送门:text

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John’s field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

输入描述

  • Line 1: Two integers: T and N

  • Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.

输出描述

  • Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

示例

输入

1
2
3
4
5
6
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

输出

1
90

Hint

INPUT DETAILS:

There are five landmarks.

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

题解

题目大意

有N个点,给出从a点到b点的距离,当然a和b是互相可以抵达的,问从1到n的最短距离

思路

模板题

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<cstdio>
#include<queue>
const int MAXN = 1e3 +5, INF = 0x3f3f3f3f;
using namespace std;
int n, m;
int d[MAXN];
vector<pair<int, int> >E[MAXN];

int main(){
while(cin >> n >> m){
memset(d, INF, sizeof(d));
for(int i = 0; i < MAXN; i++){
E[i].clear();
}
for(int i = 0; i < n; i++){
int a, b, c;
cin >> a >> b >> c;
E[a].push_back(make_pair(b, c));
E[b].push_back(make_pair(a, c));
}
priority_queue<pair<int, int> > que;
d[1] = 0 ;
que.push(make_pair(-d[1], 1));
while(!que.empty()){
int now = que.top().second;
que.pop();
for(int i = 0; i < E[now].size(); i++){
int v = E[now][i].first;
if(d[v] > d[now] + E[now][i].second){
d[v] = d[now]+E[now][i].second;
que.push(make_pair(-d[v], v));
}
}
}
cout << d[m] << endl;
}
}